﻿using FireChat.Server.Database.Table.Messages;
using FireChat.Server.Session.Receiver;
using FireChat.Share.Database.Util;
using FireChat.Share.Web.Actions;
using FireChat.Share.Web.Model.Enums;
using FireChat.Share.Web.Model.Response;
using FireChat.Share.Web.Package;

namespace FireChat.Server.Database.Manager;


/// <summary>
/// 消息管理
/// </summary>
internal static class MessageManager
{
    /// <summary>
    /// 接收到客户端发送的消息
    /// </summary>
    public static ServerPackage MessageReceived(this PackageReceiver receiver, int senderId, string content, int targetId, AccountType targetType)
    {
        MessageData msg = new()
        {
            AccountId = senderId,
            Content = content,
            TargetId = targetId,
            TargetType = targetType,
            IsRead = false
        };

        var count = DataTableManager<MessageData>.Insert(msg);
        if (count <= 0) return receiver.ReplyFailureAsync("发送失败");


        var sender_username = AccountManager.GetInstance(x => x.Id == senderId)?.Username;
        if(sender_username == null)
        {
            return receiver.ReplyFailureAsync("无法获取用户名");
        }

        //TODO: 发送消息  测试一波

        FriendMessageResponse resp_package = new()
        {
            SenderUsername = sender_username,
            Content = content,
        };

        //发给在线的联系人
        var online_target = AccountManager.LoginAccountSession.Where(x => x.AccountToken.UID == targetId);
        foreach (var i in online_target)
        {
            i.SendAsync(ClientActions.Message.CreatePackage(true, "收到消息", resp_package));
        }

        return receiver.ReplySuccessAsync("发送成功");
    }
}
